<template>
  <div class="department-container">
    <div class="app-container permissions">
      <el-card>
        <!-- 具体页面结构 -->
        <div style="text-align: right">
          <el-button type="primary" size="small" @click="hAdd(1, '0')">
            <i class="el-icon-edit" />
            添加权限
          </el-button>
        </div>
        <el-table :data="list" row-key="id" style="width: 100%">
          <el-table-column label="菜单名称" width="220">
            <template v-slot="{ row }">
              <i class="el-icon-folder-opened" /> {{ row.name }}
            </template>
          </el-table-column>
          <el-table-column prop="code" label="权限标识" width="250" />
          <el-table-column prop="description" label="描述" width="250" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <!-- type为1时为页面级访问权限，它可以继续做添加： 设置页面下边某个功能是否可以操作 -->
              <!-- type为2时为按钮级别的访问权限，它就不能再继续细分了，它就没有添加了 -->
              <el-button
                v-if="row.type === 1"
                type="text"
                @click="hAdd(2, row.id)"
              >添加权限点</el-button>
              <el-button type="text">查看api权限</el-button>
              <el-button type="text" @click="doEdit(row.id)">查看</el-button>
              <el-button type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-dialog
      :visible.sync="showDialog"
      :title="isEdit ? '查看编辑' : '添加权限'"
      @close="resectForm"
    >
      <!-- 表单内容 -->
      <el-form
        ref="formList"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label=" 权限名称" prop="name">
          <el-input v-model.trim="formData.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model.trim="formData.code" />
        </el-form-item>
        <el-form-item label="权限描述">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="权限启用">
          <el-switch
            v-model="formData.enVisible"
            active-text="启用"
            active-value="1"
            inactive-text="不启用"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: right">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="ohSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  getPermissionList,
  addPermission,
  delPermission,
  updatePermission,
  getPermissionDetail
} from '@/api/permisson.js'
import { ToDoLostData } from '@/utils'
export default {
  data() {
    const valiCode = (rule, value, callback) => {
      // 添加时的校验：code 不能重复
      let existCodeList = this.originList
      if (this.isEdit) {
        // 编辑时的校验：code 能取自己
        existCodeList = this.originList.filter(
          item => item.id !== this.formData.id
        )
      }
      // 判断当前添加项中的 权限标识 在数据库中是否被占用
      existCodeList.map(e => e.code).includes(value)
        ? callback(new Error(value + '已占用'))
        : callback()
    }
    const valiName = (rule, value, callback) => {
      // 添加时的校验：名字不能取元素名
      const existNameList = this.originList.filter(
        item => item.pid === this.formData.pid
      )
      if (this.isEdit) {
        // 编辑时的校验： 名字不能取兄弟（排除自己）的名字
        // 找兄弟，排除自己
        existNameList.filter(
          item => item.pid === this.formData.pid && item.id !== this.formData.id
        )
      }
      existNameList.map(e => e.name).includes(value)
        ? callback(new Error(value + '已占用'))
        : callback()
    }
    return {
      list: [],
      isEdit: null,
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      originList: [],
      rules: {
        name: [
          { required: true, message: '请填入名称', trigger: 'blur' },
          {
            validator: valiName,
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '请填入权限标识', trigger: 'blur' },
          {
            validator: valiCode,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 获取权限列表
    async loadPermissionList() {
      const { data } = await getPermissionList()
      this.originList = data.map(({ id, pid, name, code }) => ({
        id,
        pid,
        name: name,
        code
      }))
      // 将数据处理成树形结构
      this.list = ToDoLostData(data, '0')
    },
    // 添加权限
    hAdd(type, id) {
      this.isEdit = false
      this.showDialog = true
      // 记录当前添加的关键信息
      this.formData.type = type
      this.formData.pid = id
    },
    // 用户点击了确定
    ohSubmit() {
      this.$refs.formList.validate(vali => {
        if (vali) {
          this.isEdit ? this.hEdit() : this.odAdd()
        }
      })
    },
    // 添加权限函数
    async odAdd() {
      try {
        await addPermission(this.formData)
        // 重新加载数据
        this.loadPermissionList()
        // 关闭弹出层
        this.showDialog = false
        this.$message.success('添加成功')
      } catch (error) {
        this.$message.error('添加失败')
        console.log(error)
      }
    },
    // 删除权限
    hDel(id) {
      this.$confirm('您确认删除吗')
        .then(() => {
          // 确定删除
          this.ohDel(id)
        })
        .catch(() => {})
    },
    async ohDel(id) {
      try {
        await delPermission(id)
        // 重新加载数据
        this.loadPermissionList()
        // 关闭弹出层
        this.showDialog = false
        this.$message.success('删除成功')
      } catch (error) {
        this.$message.error('删除失败')
        console.log(error)
      }
    },
    // 根据id查看编辑权限
    async doEdit(id) {
      //  用户点击了编辑
      this.isEdit = true
      const { data } = await getPermissionDetail(id)
      // 将获取的数据渲染到页面
      this.formData = data
      // 打开弹出层
      this.showDialog = true
    },
    // 查看更新数据
    async hEdit() {
      try {
        await updatePermission(this.formData)
        // 重新加载数据
        this.loadPermissionList()
        // 关闭弹出层
        this.showDialog = false
        this.$message.success('编辑成功')
      } catch (error) {
        this.$message.error('编辑失败')
        console.log(error)
      }
    },
    // 当弹层关闭时，重置表单
    resectForm() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      //  清空校验
      this.$refs.formList.resetFields()
    }
  }
}
</script>

<style lang="scss">
.permissions {
  td {
    padding: 8px 0 !important;
  }
}
.el-dialog__body {
  padding: 0 !important;
}
</style>

<style lang="scss" scoped>
.el-form {
  padding: 30px 20px;
}
</style>
